/**
 * MIT License
 * 
 * Copyright (c) 2017 CaiDongyu
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.tunnel.server.udp;

import com.tunnel.common.nio.EventLoopGroupManager;
import com.tunnel.common.util.LogUtil;
import com.tunnel.common.util.PortUtil;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;  
  
public class UdpServer extends Thread{  
    private int port;
    private int portIndex;
      
    public UdpServer(int port,int portIndex) throws Exception {  
        this.port = port;
        this.portIndex = portIndex;
        this.setName("UdpServer thread on port:"+port);
        
        boolean portIsUsing = PortUtil.checkPortIsUsing(port);
        if(portIsUsing){
        	throw new Exception("port "+port+" is using");
        }
    }
    
    @Override
    public void run(){
        EventLoopGroup workerGroup = new NioEventLoopGroup();  
        EventLoopGroupManager.add(port, workerGroup);
        try {
        	Bootstrap  bs = new Bootstrap()
            		.group(workerGroup)
            		.channel(NioDatagramChannel.class)
            		.option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<DatagramChannel>() {  
                        protected void initChannel(DatagramChannel ch) throws Exception {
                        	ChannelPipeline p = ch.pipeline();
                        	//只负责接收数据
                            p.addLast(new UdpServerHandler(port,portIndex));  
                        };  
                    });// Socket参数，地址复用
//            .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)  
             // 绑定端口，开始接收进来的连接  
             ChannelFuture future = bs.bind(port).sync();    
             
             LogUtil.d("udp server start listen at " + port );
             future.channel().closeFuture().sync();  
        } catch (Exception e) {
			LogUtil.e(e);
        	EventLoopGroupManager.shutdown(port);
        }  
    }	
    
    public static void main(String[] args) {
		try {
			new UdpServer(80,0).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}  